﻿using _15Net8AspNetCore_ORM.Context;
using _15Net8AspNetCore_ORM.Models;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace _15Net8AspNetCore_ORM.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DapperOrderController : ControllerBase
    {
        public DapperDBContext _DapperContext { get; set; }
        public DapperOrderController(DapperDBContext dapperDB)
        {
            _DapperContext = dapperDB;
        }

        /// <summary>
        /// 新增商品
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddOrder(Order order)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                int id = await connect.ExecuteScalarAsync<int>("insert into `Order` (name, price, price2) values (@name, @Price, @Price2) ; select LAST_INSERT_ID(); ", order);  // 获取插入的个数

                return CreatedAtAction(nameof(GetOrder), new { id = id }, new Order());
            }
        }


        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpDelete("id")]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                await connect.ExecuteAsync("delete from `Order` where id = @Id ", new { Id = id });

                return CreatedAtAction(nameof(GetAllOrder), new List<Order>());
            }
        }

        /// <summary>
        /// 修改商品
        /// </summary>
        [HttpPut("id")]
        public async Task<IActionResult> UpdateOrder(int id, Order Order)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                await connect.ExecuteAsync("update `Order` set name = @name, price = @Price, price2 = @Price2 where id = @Id ", Order);

                return CreatedAtAction(nameof(GetOrder), new { id = id }, Order);
            }
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet("id")]
        public async Task<IActionResult> GetOrder(int id)
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                Order order = await connect.QueryFirstAsync<Order>("Select * from `Order` where id = @Id ", new { Id = id });

                return Ok(order);
            }
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAllOrder()
        {
            // 1、创建链接
            using (var connect = _DapperContext.DbConnection())
            {
                List<Order> orders = connect.Query<Order>("Select * from `Order`").ToList();

                return Ok(orders);
            }
        }
    }
}

